package cn.dansj.common.utils.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.databind.util.EnumUtils;

import java.io.IOException;

class EnumSerializer<T extends Enum<T>> extends StdSerializer<Enum<T>> {
    public EnumSerializer() {
        super(Enum.class, false);
    }

    @Override
    public void serialize(Enum<T> value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        if (serializerProvider.isEnabled(SerializationFeature.WRITE_ENUMS_USING_INDEX)) {
            gen.writeNumber(value.ordinal());
            return;
        }
        if (serializerProvider.isEnabled(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)) {
            gen.writeString(EnumUtils.serialize(value, serializerProvider.getConfig()));
            return;
        }
        try {
            gen.writeEnum(value);
        } catch (NoSuchMethodError e) {
            gen.writeString(EnumUtils.serialize(value, serializerProvider.getConfig()));
        }
    }
}
